package org.wutopia.examples.elasticsearch;


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.LocalDateTime;

@RestController
@Slf4j
@AllArgsConstructor
public class ESController {

    private ElasticsearchClient esClient;

    @GetMapping("/aga")
    public String get() throws IOException {

        Haha haha = new Haha();

        haha.setId(1234L);
        haha.setName("啦啦啦");
        haha.setAuthor("喀喀喀");
        haha.setPage_count(1000L);
        haha.setRelease_date(LocalDateTime.now());


        IndexResponse response = esClient.index(i -> i
                .index("haha")
                .id(haha.getId().toString())
                .document(haha)
        );

        log.info("Indexed with version " + response.version());
        return response.version() + "";
    }


    @GetMapping("/aa")
    public String ge() throws IOException {

        String searchText = "";

        SearchResponse<Haha> response = esClient.search(s -> s
                        .index("haha")
                        .query(q -> q
                                .match(t -> t
                                        .field("name")
                                        .query(searchText)
                                )
                        )
                        .from(0)
                        .size(2)
                ,
                Haha.class
        );
        Hit<Haha> hahaHit = response.hits().hits().get(0);
        log.info("sdgasdg: {}", response.hits());

        log.info("Indexed with version " + hahaHit.source().toString());
        return hahaHit.source().toString();
    }

}
